package main

import (
	"context"
	"fmt"
	"go.etcd.io/etcd/client/v3"
	"time"
)

func main() {
	//	连接etcd
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"192.168.56.129:2379", "192.168.56.130:2379", "192.168.56.131:2379"},
		DialTimeout: time.Second * 5,
	})
	if err != nil {
		fmt.Printf("connect etcd cluster failed,err:%v\n", err)
		return
	}
	defer cli.Close()
	//	put操作
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err = cli.Put(ctx, "test", "测试")
	if err != nil {
		fmt.Printf("put to etcd failed,err:%v\n", err)
		return
	}
	cancel()
	//	get
	ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	gr, err := cli.Get(ctx, "test")
	if err != nil {
		fmt.Printf("get to etcd failed,err:%v\n", err)
		return
	}
	for _, ev := range gr.Kvs {
		fmt.Printf("key:%s value:%s\n", ev.Key, ev.Value)
	}
	cancel()
	//	watch 用来获取更改的通知 监控etcd中key的变化 实现文件的热加载
	watchChan := cli.Watch(context.Background(), "test")
	for wresp := range watchChan {
		for _, event := range wresp.Events {
			fmt.Printf("type:%s,key:%s,value:%s\n", event.Type, event.Kv.Key, event.Kv.Value)
		}
	}
}
